package com.bookocean.application.service;
import com.bookocean.application.resp.WechatLoginResp;
import com.bookocean.controller.dto.UserInfoDto;

import com.bookocean.domain.service.UserInfoDomainService;
import com.bookocean.domain.service.WeChatDomainService;
import com.bookocean.domain.utils.JwtUtils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * 用户服务实现类
 *
 * @author 简语
 * @since 2025-01-27
 */
@Slf4j
@Service
public class UserInfoService {


    @Autowired
    private WeChatDomainService weChatDomainService;

    @Autowired
    private UserInfoDomainService userInfoDomainService;

    @Autowired
    private JwtUtils jwtUtils;


    public UserInfoDto login(String code) {
        WechatLoginResp response = weChatDomainService.getLoginInfo(code);
        UserInfoDto userInfo = userInfoDomainService.getUserByOpenid(response);
        
        // 生成JWT令牌
        if (userInfo != null && userInfo.getId() != null) {
            String token = jwtUtils.generateToken(userInfo.getId(), userInfo.getOpenid());
            userInfo.setAccessToken(token);
            log.info("为用户生成JWT令牌: userId={}, openid={}", userInfo.getId(), userInfo.getOpenid());
        }
        
        return userInfo;
    }

    public UserInfoDto updateUserAvatar(UserInfoDto userInfoDto) {
        UserInfoDto updatedUserInfo = userInfoDomainService.updateUserAvatar(userInfoDto);
        
        // 为更新后的用户信息生成JWT令牌
        if (updatedUserInfo != null && updatedUserInfo.getId() != null) {
            String token = jwtUtils.generateToken(updatedUserInfo.getId(), updatedUserInfo.getOpenid());
            updatedUserInfo.setAccessToken(token);
            log.info("为更新用户信息生成JWT令牌: userId={}, openid={}", updatedUserInfo.getId(), updatedUserInfo.getOpenid());
        }
        
        return updatedUserInfo;
    }
}
